<?php
/**
 * Created by PhpStorm.
 * User: Mmx
 * Date: 2021\06\08
 * Time: 14:50
 */

namespace app\backend\controller\v4;

use app\backend\validate\QuestionValidate;
use app\common\models\Question as QuestionModel;
use app\common\models\Paper;
use app\common\models\Course;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Question extends BaseController
{
    /**
     * 题库管理
     *
     * @return \think\Response
     */
    public function index()
    {
        // 题库表
        $where = input('title');//题目名称
        // 分页、排序等
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 10);
        $list = QuestionModel::field('*')
            ->where(function ($query) use ($where) {
                if ($where) {
                    $query->where('title', 'like', '%' . $where . '%');
                }
            })
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();
        $count = QuestionModel::count();
        $maxpage = ceil($count / $pageSize);
        foreach ($list as &$value) {
            $value['grade_id'] = $value->grade->title;
            $value['course_id'] = $value->course->title;
            $value['paper_id'] = $value->paper->title;
            $value['content'] = json_decode($value['content']);
            unset($value->grade);
            unset($value->course);
            unset($value->paper);
            $value['image'] = config("app.domain_url") . $value['image'];
        }
        //$page = $list->render();
        //获取列表
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => $count, 'page' => $maxpage]);
    }

    //获取课程分类信息
    public function read()
    {
        $grade_id = input('id/d');
        $model = new Course();
        $models = new Paper();

        $data = $model->where('grade_id', $grade_id)->select();
        $par = $models->where(['status' => 1])->where('pid', '<>', 0)->field('id,title')->select();//查询试卷名

        return sucessMsg(200, '获取成功', ['data' => $data, 'par' => $par]);
    }

    /**
     * 添加
     *
     * @return \think\Response
     */
    public function create()
    {
        $user = new QuestionModel();
        $data = input('post.');
        try {
            validate(QuestionValidate::class)->scene('create')->check($data);
            $data['content'] = json_encode($data['content']);
            if ($user->save($data))
                return sucessMsg(200, '创建成功！');
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择要修改的id！');
        }
        $id2 = QuestionModel::find($id);
        if (empty($id2)) {
            return errMsg(400, '要修改的数据为空！');
        }
        $data = input();
        try {
            validate(QuestionValidate::class)->scene('update')->check($data);
            $data['content'] = json_encode($data['content']);
            if (QuestionModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除数据的id！');
        }
        $data = QuestionModel::find($id);
        if (empty($data)) {
            return errMsg(400, '要删除的数据为空！');
        }
        if (QuestionModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }


    //导入
    public function importExcel()
    {
        // 获取表单上传文件
        $file[] = request()->file();
        if (empty($file[0])) {
            return errMsg(400, '请上传文件！');
        }
        $key = array_keys($file[0]);
        try {
            validate([$key[0] => 'filesize:51200|fileExt:xls,xlsx'])->check($file[0]);
            $savename = \think\facade\Filesystem::putFile('topic', $file[0][$key[0]]);
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $objPHPExcel = $objReader->load(runtime_path() . 'uploads/' . $savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return errMsg(400, '数据不能为空！');
            }
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[$j - 2] = [
                    'grade' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
                    'course' => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
                    'paper' => trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()),
                    'title' => trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()),
                    'content' => trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()),
                    'answer' => trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()),
                    'desc' => trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()),

                ];
            }
            // 创建一个新数组
            $createData = [];
            // 循环数据
            foreach ($data as $k => &$v) {
                $grade = \app\common\models\Grade::where(['title' => $v['grade']])->find();
                if (empty($grade)) {
                    return errMsg(400, '请重新核对数据...');
                }
                $course = \app\common\models\Course::where(['title' => $v['course'], 'grade_id' => $grade['id']])->find();
                $paper = \app\common\models\Paper::where(['title' => $v['paper']])->find();
                if (empty($grade) || empty($course) || empty($paper) || empty($v['title']) || empty($v['content']) || empty($v['answer']) || empty($v['desc'])) {
                    unset($data[$k]);
                    return errMsg(400, '请重新核对数据...');
                } else {
                    $createData[$k]['grade_id'] = $grade->id;
                    $createData[$k]['course_id'] = $course->id;
                    $createData[$k]['paper_id'] = $paper->id;
                    $createData[$k]['title'] = $v['title'];
                    $createData[$k]['content'] = $v['content'];
                    $createData[$k]['answer'] = $v['answer'];
                    $createData[$k]['desc'] = $v['desc'];
                }
            }
            $model = new QuestionModel();
            if ($model->saveAll($createData)) {
                return sucessMsg(200, '导入成功！');
            }
            return errMsg(500, '导入失败！');
        } catch (\think\exception\ValidateException $e) {
            return errMsg(422, $e->getMessage());
        }

    }
}